package com.rd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rd.common.CommonResult;
import com.rd.pojo.SysMenu;
import com.rd.service.SysMenuService;
import com.rd.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/sys/menu")
@Slf4j
public class SysMenuController {

    @Resource
    SysMenuService sysMenuService;

    @GetMapping("/allMenus")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public CommonResult allMenus(){
        List<SysMenu> menuList = sysMenuService.list();
        return ResultUtil.buildSuccess(menuList);
    }

    /**
     * 查询所有菜单树信息
     * @return
     */
    @RequestMapping("/treeList")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public CommonResult treeList(){
        List<SysMenu> menuList = sysMenuService.list(new QueryWrapper<SysMenu>().orderByAsc("order_num"));
        return ResultUtil.buildSuccess("treeMenu",sysMenuService.buildTreeMenu(menuList));
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:menu:add')"+"||"+"hasAuthority('system:menu:edit')")
    public CommonResult save(@RequestBody SysMenu sysMenu){
        if(sysMenu.getId()==null || sysMenu.getId()==-1){
            sysMenu.setCreateTime(new Date());
            sysMenuService.save(sysMenu);
        }else{
            sysMenu.setUpdateTime(new Date());
            sysMenuService.updateById(sysMenu);
        }
        return ResultUtil.buildSuccess();
    }


    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public CommonResult findById(@PathVariable(value = "id")Long id){
        SysMenu sysMenu = sysMenuService.getById(id);
        return ResultUtil.buildSuccess(sysMenu);
    }




}
